//以"流”模式读取输入，并根据需要拆分成多个行。
//理论上，可以处理任意数量的输入数据。

package gopl

import (
	"bufio"
	"fmt"
	"os"
)

func Dup2() {
	counts := make(map[string]int)
	files := os.Args[2:]
	if len(files) == 0 {
		//no filename
		countLines(os.Stdin, counts)
	} else {
		for _, arg := range files {
			f, err := os.Open(arg)
			if err != nil {
				fmt.Fprintf(os.Stderr, "dup2:%v\n", err)
				continue
			}
			countLines(f, counts)
			f.Close()
		}
	}
	for line, n := range counts {
		fmt.Printf("%d\t%s\n", n, line)
	}
}

func countLines(f *os.File, counts map[string]int) {
	input := bufio.NewScanner(f)
	for input.Scan() {
		t := input.Text()
		if t != "" {
			counts[t]++
		} else {
			break
		}
	}
}
